package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理超时未支付订单
     */

    @Scheduled(cron = "0 * * * * ?")// 每分钟触发一次
    public void orderTimeoutTask(){
        log.info("处理超时未支付订单");
        //超过15分钟设置为取消状态
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getOrdersByStatusAndTimeLT(Orders.PENDING_PAYMENT,time);
        if(ordersList != null && !ordersList.isEmpty()){
            for (Orders o : ordersList) {
                o.setStatus(Orders.CANCELLED);
                o.setCancelReason("超时未支付订单");
                o.setCancelTime(LocalDateTime.now());
                orderMapper.update(o);
            }
        }
    }

    /**
     * 处理派送超时订单
     */

    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发一次
    public void deliveryTimeoutOrders(){
        log.info("处理派送超时订单");
        //处理昨天的派送超时未处理的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getOrdersByStatusAndTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(ordersList != null && !ordersList.isEmpty()){
            for (Orders o : ordersList) {
                o.setStatus(Orders.COMPLETED);
                orderMapper.update(o);
            }
        }
    }
}
